<?php

require_once 'vendor/autoload.php';
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Captcha\V20190722\CaptchaClient;
use TencentCloud\Captcha\V20190722\Models\DescribeCaptchaResultRequest;
use TencentCloud\Sms\V20210111\SmsClient;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\PhoneVerificationRequest;



/**
 * 发送验证码
 */
if($uri == "/api/user/send_verify_code"){
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    $postJson = json_decode(file_get_contents("php://input"));
    $mobile = $postJson->phone;
    $code = rand(100000,999999);
    

    try{
        $smsInfo = array(
            'SecertId' => 'AKIDUnvnT5aqtjNS0MTL7jAvd8awhTJ3vgEi',
            'SecretKey' => 'Wu5DPULyNaeddQ9nQsACzPdhZPDoENOK',
            'SmsSdkAppId' => '1400832171',
            'SignName' => '广西奇易电子商务有限公司',
            'TemplateId' => '1878745'
        );
        //开始发送短信服务
        $cred = new Credential($smsInfo['SecertId'], $smsInfo['SecretKey']);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("sms.tencentcloudapi.com");
        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);
        $client = new SmsClient($cred, "ap-guangzhou", $clientProfile);
        $req = new SendSmsRequest();
        $params = array(
            "PhoneNumberSet" => array( $mobile ),
            "SmsSdkAppId" => $smsInfo['SmsSdkAppId'],
            "SignName" => $smsInfo['SignName'],
            "TemplateId" => $smsInfo['TemplateId'],
            "TemplateParamSet" => array( strval($code), "5" )
        );
        $req->fromJsonString(json_encode($params));
        $resp = $client->SendSms($req);
        // 输出json格式的字符串回包
        $retJson = json_decode($resp->toJsonString(),true);
        if($retJson['SendStatusSet'][0]['Code'] == "Ok"){
            $outJson->code = 200;
            $outJson->msg = "发送成功!";
            $outJson->data = $code;

            //设置5秒有效期
            $redis->expire("sms:register:".$mobile, 300);
            $redis->set("sms:register:".$mobile,$code);
        }else{
            $outJson->code = 400;
            $outJson->msg = "发送失败!";
            $outJson->data = $code;
        }
    }
    catch(TencentCloudSDKException $e) {
        //发送短信
        $outJson->code = 200;
        $outJson->msg = "调用短信服务失败!";
        $outJson->data = $code;
        var_dump($e);

    }


    echo json_encode($outJson);
    exit;
}

/**
 * 提交验证码登录
 * 分配token
 */
if($uri == "/api/user/login/mobile_verify"){
    $postJson = json_decode(file_get_contents("php://input"));
    $phone = $postJson->phone;
    $code = $postJson->code;
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $redisCode = $redis->get("sms:register:".$phone);
    if($code == $redisCode){
        $userInfo = $cnSql->read_only("users", "user = '$phone'");
        if(!$userInfo){
            $token = md5(time().$phone);
            $cnSql->insert_json("users",array('user'=>$phone,'type'=>0,'token'=>$token));
            $userInfo = $cnSql->read_only("users", "user = '$phone'");
        }else{
            $token = md5(time().$phone);
            $cnSql->update_json("users",array('token'=>$token),"id = $userInfo[id]");
            $userInfo = $cnSql->read_only("users", "user = '$phone'");
        }
        unset($userInfo['password']);
        $outJson->code = 200;
        $outJson->msg = "登录成功";
        $outJson->data = $userInfo;
    }else{
        $outJson->code = 400;
        $outJson->msg = "验证码错误";
    }
    echo json_encode($outJson);
    exit;
}

/**
 * 账号密码登录
 */
if($uri == "/api/user/login/password"){
    $postJson = json_decode(file_get_contents("php://input"));
    $account = $postJson->account;
    $password = $postJson->password;
    $userInfo = $cnSql->read_only("users", "user = '$account'");
    if($userInfo){
        if($userInfo['password'] == $password){ 
            $token = md5(time().$account);
            $cnSql->update_json("users",array('token'=>$token),"id = $userInfo[id]");
            $userInfo = $cnSql->read_only("users", "user = '$account'");
            $outJson->code = 200;
            $outJson->msg = "登录成功";
            $outJson->data = $userInfo;
            unset($userInfo['password']);
        }else{
            $outJson->code = 400;
            $outJson->msg = "密码错误";
        }
    }else{
        $outJson->code = 400;
        $outJson->msg = "用户不存在";
    }
    echo json_encode($outJson);
    exit;
}

/**
 * 检查登录状态
 */
if($uri == "/api/user/check"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token'");
    if($userInfo){
        $outJson->data = $userInfo;
        $outJson->code = 200;
    }else{
        $outJson->code = 400;
        $outJson->msg = "用户不存在";
    }
    echo json_encode($outJson);
    exit;
}

/**
 * 获取用户信息
 */
if($uri == "/api/user/info"){
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $userInfo = $cnSql->read_only("users", "token = '$token'");
    if($userInfo){
        //统计今日收益
        $today_income = $cnSql->custom("SELECT SUM(price) AS today_income FROM submit_details WHERE user_id = $userInfo[id] AND DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(CURDATE(), '%Y-%m-%d')")[0]['today_income'];
        $outJson->data = $userInfo;
        $outJson->data['today_income'] = $today_income;
        $outJson->code = 200;
    }else{
        $outJson->code = 400;
        $outJson->msg = "用户不存在";
    }

    echo json_encode($outJson);
    exit;
}

/**
 * 添加订阅通知
 */
if($uri == "/api/user/subscribe"){
    $postJson = json_decode(file_get_contents("php://input"));
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];
    $subscribe_phone = $postJson->phone;
    // 验证手机号格式
    if(!preg_match("/^1[3456789]\d{9}$/", $subscribe_phone)) {
        $outJson->code = 400;
        $outJson->msg = "手机号格式不正确";
        echo json_encode($outJson);
        exit;
    }
    $userInfo = $cnSql->read_only("users", "token = '$token'");
    if($userInfo){
        $outJson->code = 200;
        $outJson->msg = "订阅成功";
        $cnSql->update_json("users",array('subscribe_phone'=>$subscribe_phone),"id = $userInfo[id]");
    }else{
        $outJson->code = 400;
        $outJson->msg = "用户不存在";
    }
    echo json_encode($outJson);
}

/**
 *    查询提现相关信息
 */
if ($uri == "/api/user/withdrawtixian") {  
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];  
    $userInfo = $cnSql->read_only("users", "token = '$token'");  
    
    if ($userInfo) {  
        // 获取用户的可提现余额  
        // $user_balance = $cnSql->custom("users", "user_id = {$userInfo['id']}")[0]['balance'] ?? 0;   
        
        // 获取正在提现的金额  
                // $withdrawing_amount = $cnSql->custom("SELECT SUM(balance) AS total_balance FROM withdrawal_details WHERE user_id = {$userInfo['id']} AND status = 1")[0]['total_balance'] ?? 0;  
          $withdrawing_amount = $cnSql->custom("SELECT SUM(balance) AS total_balance FROM withdrawal_details WHERE user_id = {$userInfo['id']} AND status = '1'")[0]['total_balance'] ?? 0;

        // 获取今日剩余提现次数  
        // $remaining_withdraws = $cnSql->custom("SELECT 3 - COUNT(*) AS remaining FROM withdrawal_details WHERE user_id = {$userInfo['id']} AND DATE(create_time) = CURDATE()")[0]['remaining'] ?? 0;  
        // 获取今天该用户的提现记录数量
        $withdrawal_count_today = $cnSql->custom("SELECT COUNT(*) AS count FROM withdrawal_details WHERE user_id = {$userInfo['id']} AND DATE(create_time) = CURDATE()")[0]['count'] ?? 0 ;


        // 确保剩余提现次数不为负  
        // $remaining_withdraws = max(0, $remaining_withdraws);  

        $outJson->data = [  
            'balance' => $userInfo['balance'], // 用户的可提现余额  
            // 'ceshi'=>$withdrawing_amount,
            'withdrawingAmount' => $withdrawing_amount, // 当前正在提现的金额  
            // 'count'=>$withdrawal_count_today,
            'remainingWithdraws' => 3 - $withdrawal_count_today // 今日剩余的提现次数  
        ];  
        $outJson->code = 200;  
    } else {  
        $outJson->code = 400;  
        $outJson->msg = "用户不存在";  
    }  

    echo json_encode($outJson);  
    // exit;  
}
/**
 * 查询用户提现记录
 */
if ($uri == "/api/user/getWithdrawRecords") {  
    // 获取用户 token
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];  
    
    // 根据 token 查询用户信息
    $userInfo = $cnSql->read_only("users", "token = '$token'");  
    
    // 判断用户是否存在
    if ($userInfo) {  
        // 获取用户的提现记录
        $withdraw_records = $cnSql->custom("SELECT id, balance, create_time AS createTime, status 
                                            FROM withdrawal_details 
                                            WHERE user_id = {$userInfo['id']} 
                                            ORDER BY create_time DESC");

        // 格式化返回数据
        $withdrawal_data = [];
        foreach ($withdraw_records as $record) {
            $withdrawal_data[] = [
                'id' => $record['id'],  
                'amount' => $record['balance'],  
                'createTime' => $record['createTime'],  
                'status' => $record['status']  
            ];
        }
        // 返回成功数据
        $outJson->code = 200;  
        $outJson->message = "成功";
        $outJson->data = $withdrawal_data;  // 提现记录列表
        
    } else {  
        // 如果用户不存在
        $outJson->code = 400;  
        $outJson->message = "用户不存在";  
    }  

    // 输出 JSON 格式的响应
    echo json_encode($outJson);  
}
/**
 * 用户进行提现
 */
if ($uri == "/api/user/withdraw") {  
    // 获取用户 token
    // return
    $token = $_SERVER['HTTP_ACCESS_TOKEN'];  
    $amount = $_GET['amount']; 
    // 根据 token 查询用户信息
    $userInfo = $cnSql->read_only("users", "token = '$token'");
    // if ($userInfo){
    //     $outJson->code = 400;
    //     $outJson->message = "用户不存在或没绑定微信";
    //     $outJson->data=$userInfo
    // }
     // 查询用户是否存在
    if (empty($userInfo) || empty($userInfo['wx_openid'])) {  
        // $userInfo 为空  
        // echo "用户信息为空";  
        $outJson->code = 400;
        $outJson->message = "用户不存在或没绑定微信";
    }
    // 判断今日是否还有提现次数
    $withdrawal_count_today = $cnSql->custom("SELECT COUNT(*) AS count FROM withdrawal_details WHERE user_id = {$userInfo['id']} AND DATE(create_time) = CURDATE()")[0]['count'] ?? 0 ;
    if ($withdrawal_count_today >= 3) {  
        // 如果今天的提款次数大于等于 3，执行相应的操作  
        $outJson->code = 400;
        $outJson->message = "提现次数已达上限，请明日在尝试";
    } 
    // 查询提现金额是否大于提现
    // $userId = $_POST['userId']; // 用户ID
    // $amount = $_POST['amount'];  // 提现金额（单位：分）
     // 检查余额是否足够
    $userBalance = $cnSql->custom("SELECT balance FROM users WHERE id = {$userInfo['id']}")[0]['balance'] ?? 0;
    if ($userBalance < $amount) {
        // 余额不足
        $outJson->code = 400;
        $outJson->mes = "余额不足";
        // echo json_encode($outJson);
        // exit;
    }
    // 进行查询微信运营账户剩余金额
    // $find_url='https://api.mch.weixin.qq.com/v3/merchant/fund/balance/OPERATION';
    // 提现网址url
    $amount=0.1;
    // if (empty($amount)){
    //     $outJson->code = 400;
    //     $outJson->message = "缺少金额";
    //     // echo json_encode($outJson);
    // }
    $tixian_url='http://49.232.245.24/api/v1/wxp/weixzhuanz?money='.$amount.'&openid='.$userInfo['wx_openid'];
    // 生成新订单并访问数据库
    $response = file_get_contents($tixian_url);
    if ($response === FALSE) {
        $outJson->code = 400; 
        $outJson->message = "提现时失败"; 
        // die('Error occurred while accessing the URL.');
    }
    
    // 解析返回的 JSON 数据
    $response_data = json_decode($response, true);
    if ($response_data['code'] == 1) {
        // 提取 out_batch_no
        $out_batch_no = $response_data['msg']['out_batch_no'];
    
        // 生成新的查询链接
        $zhuanzhang_url = 'http://49.232.245.24/api/v1/wxp/chaxunyunyingyue?naa=' . $out_batch_no;
    
        // 发送请求到查询接口
        $zhuanzhang_response = file_get_contents($zhuanzhang_url);
        if ($zhuanzhang_response === FALSE) {
            $outJson->code = 400; 
            // die('Error occurred while querying the transfer order.');
            $outJson->message = "查询回执单失败"; 
        }
    
        // 解析查询结果
        $zhuanzhang_data = json_decode($zhuanzhang_response, true);
        if ($zhuanzhang_data['code'] === 1 && isset($zhuanzhang_data['msg']['response']['transfer_batch'])) {
            // 提取查询结果中的相关数据
            $transfer_batch = $zhuanzhang_data['msg']['response']['transfer_batch'];
            $batch_id = $transfer_batch['batch_id'];
            $batch_status = $transfer_batch['batch_status'];
            $total_amount = $transfer_batch['total_amount'];
            $success_num = $transfer_batch['success_num'];
            $fail_amount = $transfer_batch['fail_amount'];
            if ($batch_status === "ACCEPTED") {
                // 获取提现金额和剩余余额
                $withdrawal_amount = $amount; // 提现金额
                $user_id = $userInfo['id']; // 用户ID
                $user_name=$userInfo['user'];
                $last_balance = $userInfo['balance'] - $withdrawal_amount; // 计算剩余余额
                $create_time = date("Y-m-d H:i:s"); // 当前时间
            
                // 连接 SQL 类实例
                // $sql = new sql();
                $cnSql->lock('users'); // 锁定表，确保数据一致性
            
                try {
                    // 1. 更新 users 表中的 balance 值
                    // $update_balance_data = array('balance' => $last_balance);
                    // $update_balance_where = "id = $user_id";
                    // $cnSql->update_json('users', $update_balance_data, $update_balance_where); 
                    $last_balance2=$userInfo['balance']-($amount*100);
                    $cnSql->update_json('users', array('balance' => $last_balance2), "id = $userInfo[id]");// 更新余额
            
                    // 2. 在 withdrawal_details 表中插入记录
                    $insert_details_data = array(
                        'user_id' => $userInfo['id'],
                        'balance' => $amount,
                        'last_balance' => $last_balance2,
                        'create_time' => $create_time,
                        'status' => 0, // 状态为 0
                        'batch_id' => $batch_id,
                        'out_batch_no' => $out_batch_no
                    );
                    $cnSql->insert_json('withdrawal_details', $insert_details_data); // 插入提现记录
            
                    // 提交事务（如果需要的话，具体操作可根据数据库系统调整）
                    $cnSql->unlock(); // 解锁表
                    $outJson->code = 200; 
                    // die('Error occurred while querying the transfer order.');
                    $outJson->message = "提现成功"; 
                    $outJson->data=$insert_details_data;
                    // echo "Balance updated and withdrawal details inserted successfully.";
                } catch (Exception $e) {
                    // 发生错误时回滚事务
                    $cnSql->unlock(); // 解锁表
                    $outJson->code = 400; 
                    // die('Error occurred while querying the transfer order.');
                    $outJson->message = "查询回执单失败2";
                    $outJson->data=$zhuanzhang_data;
                    echo "Error occurred: " . $e->getMessage();
                }
            }else{
                $cnSql->lock('users'); // 锁定表，确保数据一致性
                try {
                    $last_balance2=$userInfo['balance']-($amount*100);
                    $cnSql->update_json('users', array('balance' => $last_balance2), "id = $userInfo[id]");// 更新余额
            
                    // 2. 在 withdrawal_details 表中插入记录
                    $insert_details_data = array(
                        'user_id' => $userInfo['user'],
                        'balance' => $withdrawal_amount,
                        'last_balance' => $last_balance,
                        'create_time' => $create_time,
                        'status' => 2, // 状态为 0
                        'batch_id' => $batch_id,
                        'out_batch_no' => $out_batch_no
                    );
                    $cnSql->insert_json('withdrawal_details', $insert_details_data); // 插入提现记录
            
                    // 提交事务（如果需要的话，具体操作可根据数据库系统调整）
                    $cnSql->unlock(); // 解锁表
                    // $outJson->code = 400; 
                    // $outJson->code = 400; 
                    // die('Error occurred while querying the transfer order.');
                    // $outJson->message = "提现出现异常请联系客服人员2";
                    $outJson->msg = "提现成功2";
                    $outJson->code = 200;
                    $outJson->data=$zhuanzhang_data;
                    // echo "Balance updated and withdrawal details inserted successfully.";
                } catch (Exception $e) {
                    // 发生错误时回滚事务
                    $outJson->code = 400; 
                    // die('Error occurred while querying the transfer order.');
                    $outJson->message = "提现出现异常请联系客服人员3";
                    $cnSql->unlock(); // 解锁表
                    echo "Error occurred: " . $e->getMessage();
                }
            }

        }
    }    
    echo json_encode($outJson);
    exit;
    // 查询回执转账订单
    // $zhuanzhang ='http://49.232.245.24/api/v1/wxp/chaxunyunyingyue?naa=batchyishun20241737442325';
    
}


?>